import UnityPy


env_origin = UnityPy.load("data/data.unity3d")  # 以前曾经嵌入字体了的
env_done = UnityPy.load("data/_data.unity3d")  # 未处理的
env_test = UnityPy.load("data/test_data.unity3d")  # 未处理的


# 基本思路：直接把 done 里面的拿出来塞到 origin 里面

# 问题关键：还得改一下 data.m_Texture.path_id，这就很尴尬
# 先读一遍 env_origin 找到所有的 path_id

font_path_id_map = {}
font_raw_data_map = {}

font_list = [
    "FOT-TsukuMinPro-M",
    "YGO_Card_NA",
    "FOT-RODINNTLGPRO-B",
    "YGO_Card_JP",
    "FOT-KafuTechnoStd-H",
    "FOT-RodinPro-DB",
]


for obj in env_test.objects:
    if obj.type.name == "Font":
        data = obj.read()
        font_path_id_map[data.name] = {
            "m_Texture": data.m_Texture.path_id,
            "m_DefaultMaterial": data.m_DefaultMaterial.path_id,
        }

print(font_path_id_map)

font_path_id_map_origin = {}

for obj in env_origin.objects:
    if obj.type.name == "Font":
        data = obj.read()
        font_path_id_map_origin[data.name] = {
            "m_Texture": data.m_Texture.path_id,
            "m_DefaultMaterial": data.m_DefaultMaterial.path_id,
        }

print(font_path_id_map_origin)


for key, value in font_path_id_map_origin.items():
    test_item = font_path_id_map[key]
    if (
        value["m_Texture"] != test_item["m_Texture"]
        or value["m_DefaultMaterial"] != test_item["m_DefaultMaterial"]
    ):
        print(key, value)

raise SyntaxError()
for obj in env_done.objects:
    if obj.type.name == "Font":
        data = obj.read()
        data.m_Texture.path_id = font_path_id_map[data.name]["m_Texture"]
        data.m_DefaultMaterial.path_id = font_path_id_map[data.name][
            "m_DefaultMaterial"
        ]
        data.save()
        # font_raw_data_map[data.name] = obj.get_raw_data()

with open("output/done_data.unity3d", "wb") as f:  # 其实就是拿到文件名 写入而已
    f.write(env_done.file.save())

env_done = UnityPy.load("output/done_data.unity3d")
for obj in env_done.objects:
    if obj.type.name == "Font":
        data = obj.read()
        font_raw_data_map[data.name] = obj.get_raw_data()

for obj in env_origin.objects:
    if obj.type.name == "Font":
        data = obj.read()
        print(data.name)
        if data.name not in list(font_raw_data_map.keys()):
            continue
        if data.name not in font_list:
            continue
        obj.set_raw_data(font_raw_data_map[data.name])
        data.m_Texture.path_id = font_path_id_map[data.name]["m_Texture"]
        data.m_DefaultMaterial.path_id = font_path_id_map[data.name][
            "m_DefaultMaterial"
        ]
        data.save()

with open("output/data.unity3d", "wb") as f:  # 其实就是拿到文件名 写入而已
    f.write(env_origin.file.save())
